<script setup>
import {useUserStore} from "../store/user.js";
import {useRouter, useRoute} from 'vue-router'
import {ElMessage} from 'element-plus'

const userStore = useUserStore();
const router = useRouter();

function logout() {
    userStore.setToken(undefined, undefined)
}

function openCart() {
    if (!userStore.token) {
        // 如果没有登录 跳转到登录页面
        ElMessage.error("请先登录");
        router.push("/login")
    } else {
        router.push("/cart")
    }

}
</script>

<template>
    <el-menu
        class="el-menu-demo"
        mode="horizontal"
        :ellipsis="false"
    >
        <div>
            <el-link :underline="false" class="logo" @click="router.push('/')">
                <img
                    src="../assets/banner.jpg"
                    alt="Element logo"
                />
            </el-link>
        </div>
        <el-row class="flex-grow">
            <el-col :span="14" :offset="2">
                <el-input placeholder="请输入商品名称" size="large">
                </el-input>
            </el-col>
            <el-col :span="2" :offset="1">
                <el-button type="danger" size="large">搜索</el-button>
            </el-col>
            <el-col :span="3" :offset="1">
                <el-button type="danger" plain size="large" @click="openCart">我的购物车</el-button>
            </el-col>
        </el-row>
        <el-menu-item index="1">
            <el-button type="success" plain size="large" @click="router.push('/orderInfo')">我的订单</el-button>
        </el-menu-item>
        <!--如果已经登录就显示详细信息-->
        <el-sub-menu index="2" v-if="userStore.token">
            <template #title>你好，{{ userStore.username }}</template>
            <el-menu-item index="2-1">个人中心</el-menu-item>
            <el-menu-item index="2-2" @click="logout">注销</el-menu-item>
            <el-menu-item index="2-3">...</el-menu-item>
        </el-sub-menu>
        <el-row v-else class="flex-grow">
            <el-col :span="4" :offset="14">
                <el-link type="danger" @click="router.push('/login')">登录</el-link>
            </el-col>
            <el-col :span="4" :offset="1">
                <el-link type="primary" @click="router.push('/register')">注册</el-link>
            </el-col>
        </el-row>
    </el-menu>
</template>

<style scoped>
.flex-grow {
    flex-grow: 1;
}

.logo {
    width: 200px;
    height: 100%;
    display: flex;
    align-items: center;
}

.logo img{
    width: 80%;
}

.el-link {
    font-size: 16px !important;
}

.el-row {
    align-items: center;
}
</style>